package com.tmt.datatable.editor.impl;

import com.tmt.datatable.editor.IFileDataHolder;
import com.tmt.helper.DateHelper;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * Created by ThreeManTeam on 2017/6/3.
 */
public class DefaultFileDataHolder implements IFileDataHolder {

    protected String fieldName;

    protected MultipartFile fileData;

    protected String fileName;

    public DefaultFileDataHolder() {
    }

    public DefaultFileDataHolder(String fieldName, MultipartFile fileData) {
        this.fieldName = fieldName;
        this.fileData = fileData;
        String[] flName = this.fileData.getOriginalFilename().split("\\\\");
        this.fileName = getNewFileName(flName[flName.length - 1]);
    }

    @Override
    public void setFieldName(String fieldName) {
        this.fieldName = fieldName;
    }

    @Override
    public synchronized void setFileData(Object fileData) {
        if (this.fileData == null) {
            this.fileData = (MultipartFile) fileData;
            this.fileName = getNewFileName(this.fileData.getOriginalFilename());
        }
    }

    @Override
    public String getFieldName() {
        return fieldName;
    }

    @Override
    public String getFileName() {
        return fileName;
    }

    @Override
    public Long getFileLength() {
        return fileData.getSize();
    }

    @Override
    public void transferTo(File file) throws IOException {
        fileData.transferTo(file);
    }

    @Override
    public void validate(Class<?> clazz, String propName) throws Exception{

    }

    @Override
    public IFileDataHolder newInstance() {
        return new DefaultFileDataHolder();
    }

    private String getNewFileName(String oldName) {
        String[] infos = oldName.trim().split("\\.");
        String suffix = "." + (infos.length > 1 ? infos[infos.length - 1].trim() : "");
        String time = DateHelper.formatDate(new Date(), "yyyyMMddHHmmss");
        return String.format("%s_%s%s", UUID.randomUUID().toString(), time, suffix);
    }

}
